<?php


namespace app\platform\system\service;


use app\common\model\Merchant;
use app\common\model\SysAdmin;
use app\common\model\SysMenu;
use app\common\model\SysRole;
use app\common\model\SysRoleMenu;

class AdminService
{
    const SUPPER_PERMISSION = ["*"];

    /**
     * @param string $password 密码明文
     * @param string $pwd 密文
     * @param string $slat 密码盐
     * @return bool
     */
    static function checkPassword($password, $pwd, $slat)
    {
        return $pwd === self::getPassword($password, $slat);
    }

    static function getPassword($password, $slat)
    {
        return md5(md5($password) . $slat);
    }

    static function isSuperAdmin($uid)
    {
        $role_ids = self::getRoleIdsByUid($uid);
        if (!$role_ids) {
            return false;
        }
        return self::isSuperAdminRole($role_ids);
    }

    static function getRoleIdsByUid($uid)
    {
        $data = SysAdmin::where([
            'id' => $uid
        ])->value("role_ids");
        if (!$data) {
            return [];
        }
        return explode(',', $data);
    }

    static function isSuperAdminRole($role_ids)
    {
        $count = SysRole::where([
            ['roleId', 'in', $role_ids],
            ['isSuperAdmin', '=', 1],
        ])
            ->count();
        return $count > 0;
    }

    static function getRoleNames($uid)
    {
        $role_ids = self::getRoleIdsByUid($uid);
        if (!$role_ids) {
            return false;
        }
        return SysRole::where([
            ['roleId', 'in', $role_ids],
        ])
            ->column('roleName');
    }

    static function getLoginAuthority($uid)
    {
        $data = SysAdmin::where([
            'id' => $uid
        ])->value("role_ids");
        if (!$data) {
            return [];
        }
        $role_ids = explode(',', $data);
        if (self::isSuperAdminRole($role_ids)) {
            return self::SUPPER_PERMISSION;
        }

        $data = SysMenu::alias('a')
            ->join(SysRoleMenu::getTable() . ' b', 'a.menuId=b.menu_id')
            ->where('b.role_id', 'in', $role_ids)
            ->order("a.sorted")
            ->column('a.auth');
        return $data;
    }

    static function getAuthority($uid, $menuType)
    {
        $data = SysAdmin::where([
            'id' => $uid
        ])->value("role_ids");
        if (!$data) {
            return [];
        }
        $role_ids = explode(',', $data);
        if (self::isSuperAdminRole($role_ids)) {
            return self::SUPPER_PERMISSION;
        }
        $data = SysMenu::alias('a')
            ->join(SysRoleMenu::getTable() . ' b', 'a.menuId=b.menu_id')
            ->where('b.role_id', 'in', $role_ids)
            ->where('a.menuType', 'in', $menuType)
            ->order("a.sorted")
            ->column('a.auth');
        return $data;
    }

    static function getAdminName($uid)
    {
        return SysAdmin::where("id", "=", $uid)->value("username");
    }
}